package ru.sis.shop.servlets;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import ru.sis.shop.model.Item;

/**
 * Servlet implementation class ItemModifyController.
 */
@WebServlet("/item_modify")
@MultipartConfig
public final class ItemModifyController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6478427352370516639L;

//	private static final Logger logger = LoggerFactory.getLogger(ItemModifyController.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
			throws ServletException, IOException {
		long id = 0;
		try {
			final String param = request.getParameter("id");
			id = (param == null) ? 0 : Long.parseLong(param);
		} catch (final NumberFormatException e) {
			response.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
			return;
		}

		final SessionFactory factory = (SessionFactory) getServletContext().getAttribute(
				"sessionFactory");
		final Session session = factory.openSession();
		session.beginTransaction();
		try {
			// FIXME null -> new Item(...)
			final Item item = (id == 0) ? null : (Item) session.get(Item.class, id);
			if (item == null) {
				response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
				return;
			}

			request.setAttribute("item", item);
			final RequestDispatcher dispatcher = request.getRequestDispatcher("item_modify.jsp");
			dispatcher.forward(request, response);
		} finally {
			session.close();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");

		final String idParam = request.getParameter("id");
		if (idParam == null) {
			response.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
			return;
		}
		
		final long id;
		try {
			id = Long.parseLong(idParam);
		} catch (final NumberFormatException e) {
			response.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
			return;
		}

		final SessionFactory factory = (SessionFactory) getServletContext().getAttribute(
				"sessionFactory");
		final Session session = factory.openSession();
		Transaction transaction = session.beginTransaction();
		try {
			if (Boolean.parseBoolean(request.getParameter("remove"))) {
				hanldeRemove(id, session, request, response);
			} else {
				// FIXME null -> new Item(...)
				Item item =  (id == 0) ? null : (Item) session.load(Item.class, id);
				handleModify(item, session, request, response);
			}
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw e;
		} finally {
			session.close();
		}

		response.sendRedirect("goods");
	}

	private void hanldeRemove(final Long id, final Session session,
			final HttpServletRequest request, final HttpServletResponse response) {
		final Item item = (Item) session.get(Item.class, id);
		session.delete(item);
	}

	private void handleModify(final Item item, final Session session,
			final HttpServletRequest request, final HttpServletResponse response) {
		item.setName(request.getParameter("name"));
		item.setDescription(request.getParameter("description"));
		item.setCost(Integer.parseInt(request.getParameter("cost")));
		item.setWidth(new BigDecimal(request.getParameter("width")));
		item.setHeight(new BigDecimal(request.getParameter("height")));
		item.setDepth(new BigDecimal(request.getParameter("depth")));

//		final Image mainImage = getImage(request, "mainImage");
//		if (mainImage != null) {
//			final Image oldImage = item.getMainImage();
//
//			item.setMainImage(mainImage);
//			session.save(mainImage);
//
//			if (oldImage != null) {
//				session.delete(oldImage);
//			}
//		}

		session.save(item);
	}

//	private Image getImage(final HttpServletRequest request, final String name) {
//		Part part;
//		try {
//			part = request.getPart(name);
//		} catch (IllegalStateException | IOException | ServletException e) {
//			logger.warn("While loading image throw expection ", e);
//			return null;
//		}
//
//		if (part == null || part.getSize() <= 0) {
//			return null;
//		}
//
//		final Image mainImage = new Image();
//		mainImage.setContentType(part.getContentType());
//		mainImage.setFileName(ItemModifyController.getFilename(part));
//		
//		try (InputStream is = part.getInputStream()) {
//			mainImage.setImage(ByteStreams.toByteArray(is));
//		} catch (IOException e) {
//			logger.warn("While loading image throw expection ", e);
//			return null;
//		}
//
//		final ByteArrayInputStream is = new ByteArrayInputStream(mainImage.getImage());
//		final ByteArrayOutputStream os = new ByteArrayOutputStream();
//		try {
//			Thumbnails.of(is).size(Image.THUMBNAILS_WIDTH, Image.THUMBNAILS_HEIGHT)
//					.toOutputStream(os);
//			mainImage.setThumbnails(os.toByteArray());
//		} catch (IOException e) {
//			logger.warn("Can't make thumtnails", e);
//		}
//
//		return mainImage;
//	}

//	private static String getFilename(final Part part) {
//		for (final String cd : part.getHeader("content-disposition").split(";")) {
//			if (cd.trim().startsWith("filename")) {
//				final String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
//				return filename.substring(filename.lastIndexOf('/') + 1).substring(
//						filename.lastIndexOf('\\') + 1); // MSIE
//			}
//		}
//		return null;
//	}
}
